<template>
  <div class="main">
    <el-form :inline="true" :model="roleSearchModel" :label-width="100" label-position="right" ref="searchFormRef">
      <el-form-item label="ID：" prop="id">
        <el-input v-model="roleSearchModel.id" placeholder="请输入角色ID"/>
      </el-form-item>
      <el-form-item label="名称：" prop="name">
        <el-input v-model="roleSearchModel.name" placeholder="请输入角色名称"/>
      </el-form-item>
    </el-form>

    <!-- 按钮区 -->
    <div class="action">
      <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
      <el-button type="primary" :icon="Edit" @click="edit">修改</el-button>
      <el-button type="primary" :icon="Search" @click="findAll">查询</el-button>
      <el-button type="primary" :icon="Refresh" @click="resetSearchForm">重置</el-button>
      <el-button type="danger" :icon="Delete" @click="deleteAll">删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table class="data-grid" :data="roles" stripe border @row-click="tblRowClick" ref="tblRef">
      <el-table-column type="selection" align="center"/>
      <el-table-column prop="id" label="ID" width="70" fixed="left"/>
      <el-table-column prop="name" label="角色名称" width="180" fixed="left"/>
      <el-table-column prop="enabled" label="是否启用" width="100" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.enabled" inline-prompt active-text="是" inactive-text="否" @click.stop=""@change="enabledChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="备注" width="500" show-overflow-tooltip/>
      <el-table-column prop="createdTime" label="创建时间" width="180"/>
      <el-table-column prop="createdBy" label="创建人" width="120"/>
      <el-table-column prop="updatedTime" label="修改时间" width="180"/>
      <el-table-column prop="updatedBy" label="修改人" width="120"/>

      <el-table-column label="操作" fixed="right" width="250" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click.stop="permDetail(scope.row)" :icon="Setting">权限</el-button>
          <el-button size="small" type="primary" @click.stop="editRow(scope.row)" :icon="Edit">修改</el-button>
          <el-button size="small" type="danger" @click.stop="deleteRow(scope.row)" :icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条中的页面大小必须和查询函数中的页面大小匹配，否则会出现多次查询 -->
    <el-pagination class="page" v-model:current-page="pi.pageNo" v-model:page-size="pi.pageSize" :total="pi.total"
                   :page-sizes="[10, 20,30, 50, 100]" background
                   layout="total, sizes, prev, pager, next, jumper"
                   @change="findAll"/>
  </div>

  <!-- 弹出新增对话框 -->
  <el-dialog :title="dialogTitle" v-model="showDialog" draggable :close-on-click-modal="false"
             @close="onCloseDialog()" style="width: 700px">
    <div>
      <el-form label-width="100" :model="roleModel" :rules="rules" ref="roleFormRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称：" prop="name">
              <el-input v-model="roleModel.name" placeholder="请输入角色名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用：" prop="enabled">
                <template #default="scope">
                    <el-switch v-model="roleModel.enabled" inline-prompt active-text="是" inactive-text="否" />
                </template>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注：" prop="description">
              <el-input v-model="roleModel.description" type="textarea" :rows="5" placeholder="请输入角色备注"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <template #footer>
      <div class="footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="showDialog = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 权限详情 -->
  <el-dialog title="权限" v-model="showPermDialog" draggable :close-on-click-modal="false" width="700"
             destroy-on-close>
    <role-perm :role-id="roleId"/>
  </el-dialog>
</template>

<style scoped>
.main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page {
  margin-top: 10px;
}

.data-grid {
  margin-top: 10px;
}
</style>

<script setup>
import {findAllRole,deleteRoleById,saveRole,updateRole} from "@/api/RoleApi.js";
import {reactive, ref, onMounted, toRaw, nextTick} from 'vue';
import {CirclePlus, Delete, Edit, Refresh, Search, Setting} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
// import GroupRole from "@/components/views/GroupRole.vue";
import RolePerm from "@/components/RolePerm.vue";

let roles = ref();//所有角色数据

// 查询表单双向绑定数据
let roleSearchModel = reactive({
  id: null,
  name: null
});

// 分页信息
let pi = reactive({
  pageNo: 1,
  pageSize: 15,
  total: 0
});

onMounted(() => {
  findAll();
});

// 查询全部
async function findAll() {
  let params = toRaw(roleSearchModel);//克隆一份

  //添加分页参数
  // params.pageNo = pi.pageNo;
  // params.pageSize = pi.pageSize;

  let resp = await findAllRole(pi.pageNo, pi.pageSize,params);
    console.log(resp);

  if (resp) {
      console.log(resp.data);
    roles.value = resp.records;
    pi.pageNo = resp.current;
    pi.pageSize = resp.size;
    pi.total = resp.total;
  } else {
    pi.total = 0;
  }
}

let searchFormRef = ref();

// 重置查询表单
function resetSearchForm() {
  searchFormRef.value.resetFields();
}

///////////////////////////////////////////////////////////
const tblRef = ref();

function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

// 批量删除全部
function deleteAll() {
  let rows = tblRef.value.getSelectionRows();
  let ids = rows.map(t => t.id);
  if (ids.length === 0) {
    ElMessage.warning("请选择您要删除的行");
  } else {
    ElMessageBox.confirm("是否确认删除选中的行?", "警告", {
      type: "warning"
    }).then(() => {
      deleteByIds(ids);
    }).catch(error => {
      //do nothing
    });
  }
}

//删除当前前
function deleteRow(row) {
  ElMessageBox.confirm("是否确认删除选中的行?", "警告", {
    type: "warning"
  }).then(() => {
    deleteByIds([row.id]);
  }).catch(error => {
    //do nothing
  });
}

//根据id批量删除
async function deleteByIds(ids) {
  let resp = await deleteRoleById(ids);
  console.log(resp);
  if (resp.code==='200') {
    ElMessage.success("操作成功，共删除" + resp.data + "行");
    await findAll();//重新加载
  } else {
    ElMessage.error(resp.msg || "操作失败");
  }
}

///////////////////////////////////////////////////////////////
let dialogTitle = ref("新增角色");
let showDialog = ref(false);
let roleFormRef = ref();
let mode = "add";//操作模式

// 添加或修改角色的表单数据
let roleModel = ref({
  name: null,
  enabled: true,
  description: null
});

// 表单验证规则
const rules = {
  name: [{
    required: true, message: "角色名称不可为空", trigger: "blur"
  }]
};

//清空对话框
function onCloseDialog() {
  roleFormRef.value.resetFields();//清空表单内容
}

function add() {
  dialogTitle.value = "新增角色";
  showDialog.value = true;
  mode = "add";
}

//点击确定按钮，提交
function submit() {
  if (mode === "add") {
    submitAdd();
  } else {
    submitEdit();
  }
}

//提交教练数据
function submitAdd() {
  roleFormRef.value.validate(async valid => {
    if (valid) {
      let user = toRaw(roleModel.value);
      user.id = null;
      let resp;
      try {
        resp = await saveRole(user);
      } catch (error) {
        console.log(error);
        ElMessage.error(error.msg || "保存角色失败");
        return;
      }

      if (resp.code === '200') {
        ElMessage.success("保存角色成功");
        showDialog.value = false;//关闭窗口
        await findAll();
      } else {
        ElMessage.error(resp.msg || "保存角色失败");
      }
    } else {
      ElMessage.warning("输入不正确");
    }
  });
}

///////////////////////////////////////////////////////////
// 修改角色
function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows.length === 0) {
    ElMessage.warning("请选中您要修改的行");
  } else if (rows.length > 1) {
    ElMessage.warning("您一次只能修改一行");
  } else {
    editRow(rows[0]);
  }
}

function editRow(row) {
  dialogTitle.value = "修改角色";
  showDialog.value = true;
  mode = "edit";

  nextTick(() => {
    row = cloneDeep(toRaw(row));
    roleModel.value = row;
  });
}

//提交教练数据
function submitEdit() {
  roleFormRef.value.validate(async valid => {
    if (valid) {
      let role = toRaw(roleModel.value);
      let resp;

      try {
        resp = await updateRole(role);
      } catch (error) {
        ElMessage.error(error.msg || "修改角色失败");
        return;
      }

      if (resp.code==="200") {
        ElMessage.success("修改角色成功");
        showDialog.value = false;//关闭窗口
        await findAll();
      } else {
        ElMessage.error(resp.msg || "修改角色失败");
      }
    } else {
      ElMessage.warning("输入不正确");
    }
  });
}
async function enabledChange(row){
    const updateDate ={
        id:row.id,
        enabled:row.enabled
    }
    let resp = await updateRole(updateDate);
    console.log(resp);
    if (resp.code === '200') {
        ElMessage.success("状态更新成功");
    } else {
        // 如果更新失败，回滚状态
        row.enabled = !row.enabled;
        ElMessage.error(resp.msg || "状态更新失败");
    }
}
//////////////////////////////////////////////////
const showPermDialog = ref(false);
const roleId = ref();//角色编号

function permDetail(row) {
  showPermDialog.value = true;
  roleId.value = row.id;
}
</script>